import React, { useState, useEffect } from 'react';
import { Badge, Tooltip, Button, Progress, Tag, Statistic, Card } from 'antd';
import { 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  LoadingOutlined,
  QuestionCircleOutlined,
  ReloadOutlined,
  WarningOutlined,
  ClockCircleOutlined,
  ThunderboltOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import './style.css';

interface ModelStatusIndicatorProps {
  status: 'healthy' | 'unhealthy' | 'checking' | 'unknown' | 'warning';
  lastChecked?: Date;
  onTest?: () => void;
  showTestButton?: boolean;
  size?: 'small' | 'default';
  responseTime?: number;
  errorCount?: number;
  uptime?: number;
  showDetails?: boolean;
  healthScore?: number;
  lastError?: string;
}

interface StatusMetrics {
  avgResponseTime: number;
  errorRate: number;
  uptime: number;
  lastErrors: string[];
}

const ModelStatusIndicator: React.FC<ModelStatusIndicatorProps> = ({
  status,
  lastChecked,
  onTest,
  showTestButton = false,
  size = 'default',
  responseTime,
  errorCount = 0,
  uptime = 0,
  showDetails = false,
  healthScore,
  lastError
}) => {
  const [detailsVisible, setDetailsVisible] = useState(false);
  const [metrics, setMetrics] = useState<StatusMetrics>({
    avgResponseTime: responseTime || 0,
    errorRate: 0,
    uptime: uptime,
    lastErrors: lastError ? [lastError] : []
  });

  useEffect(() => {
    setMetrics(prev => ({
      ...prev,
      avgResponseTime: responseTime || prev.avgResponseTime,
      uptime: uptime,
      lastErrors: lastError ? [lastError, ...prev.lastErrors.slice(0, 4)] : prev.lastErrors
    }));
  }, [responseTime, uptime, lastError]);
  const getStatusConfig = () => {
    switch (status) {
      case 'healthy':
        return {
          color: '#52c41a',
          icon: <CheckCircleOutlined />,
          text: '在线',
          description: '模型运行正常',
          badgeStatus: 'success' as const
        };
      case 'unhealthy':
        return {
          color: '#ff4d4f',
          icon: <CloseCircleOutlined />,
          text: '离线',
          description: '模型连接失败',
          badgeStatus: 'error' as const
        };
      case 'checking':
        return {
          color: '#1890ff',
          icon: <LoadingOutlined spin />,
          text: '检测中',
          description: '正在检测模型状态',
          badgeStatus: 'processing' as const
        };
      case 'warning':
        return {
          color: '#faad14',
          icon: <WarningOutlined />,
          text: '警告',
          description: '模型响应缓慢或不稳定',
          badgeStatus: 'warning' as const
        };
      case 'unknown':
      default:
        return {
          color: '#d9d9d9',
          icon: <QuestionCircleOutlined />,
          text: '未知',
          description: '尚未检测模型状态',
          badgeStatus: 'default' as const
        };
    }
  };

  const config = getStatusConfig();
  
  const getTooltipContent = () => {
    if (showDetails) {
      return null; // 当显示详细信息时，不显示简单tooltip
    }
    
    const content = [config.description];
    
    if (lastChecked) {
      const timeAgo = getTimeAgo(lastChecked);
      content.push(`最后检测: ${timeAgo}`);
    }
    
    if (responseTime) {
      content.push(`响应时间: ${responseTime}ms`);
    }
    
    if (errorCount > 0) {
      content.push(`错误次数: ${errorCount}`);
    }
    
    if (healthScore !== undefined) {
      content.push(`健康评分: ${healthScore}%`);
    }
    
    return content.join('\n');
  };

  const getHealthColor = (score: number) => {
    if (score >= 90) return '#52c41a';
    if (score >= 70) return '#faad14';
    return '#ff4d4f';
  };

  const getResponseTimeStatus = (time: number) => {
    if (time < 500) return 'success';
    if (time < 2000) return 'normal';
    if (time < 5000) return 'warning';
    return 'exception';
  };

  const renderDetailedStatus = () => {
    if (!showDetails) return null;

    return (
      <Card 
        className="status-details-card"
        size="small"
        title={
          <span>
            <InfoCircleOutlined /> 状态详情
          </span>
        }
        style={{ marginTop: 8, maxWidth: 300 }}
      >
        <div className="status-metrics">
          {healthScore !== undefined && (
            <div className="metric-item">
              <span className="metric-label">健康评分</span>
              <Progress 
                percent={healthScore} 
                size="small" 
                strokeColor={getHealthColor(healthScore)}
                showInfo={false}
              />
              <span className="metric-value">{healthScore}%</span>
            </div>
          )}
          
          {responseTime && (
            <div className="metric-item">
              <span className="metric-label">
                <ThunderboltOutlined /> 响应时间
              </span>
              <Statistic 
                value={responseTime} 
                suffix="ms" 
                valueStyle={{ 
                  fontSize: 12,
                  color: getResponseTimeStatus(responseTime) === 'success' ? '#52c41a' : 
                         getResponseTimeStatus(responseTime) === 'warning' ? '#faad14' : '#ff4d4f'
                }}
              />
            </div>
          )}
          
          {uptime > 0 && (
            <div className="metric-item">
              <span className="metric-label">
                <ClockCircleOutlined /> 正常运行时间
              </span>
              <span className="metric-value">
                {uptime >= 24 ? `${Math.floor(uptime / 24)}天` : `${uptime}小时`}
              </span>
            </div>
          )}
          
          {errorCount > 0 && (
            <div className="metric-item">
              <span className="metric-label">错误计数</span>
              <Tag color="error">{errorCount}</Tag>
            </div>
          )}
          
          {lastChecked && (
            <div className="metric-item">
              <span className="metric-label">最后检测</span>
              <span className="metric-value">{getTimeAgo(lastChecked)}</span>
            </div>
          )}
          
          {metrics.lastErrors.length > 0 && (
            <div className="metric-item">
              <span className="metric-label">最近错误</span>
              <div className="error-list">
                {metrics.lastErrors.slice(0, 2).map((error, index) => (
                  <div key={index} className="error-item">
                    <Tag color="error" size="small">{error}</Tag>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </Card>
    );
  };

  const getTimeAgo = (date: Date): string => {
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 1) {
      return '刚刚';
    } else if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else {
      return `${diffDays}天前`;
    }
  };

  return (
    <div className={`model-status-indicator ${size}`}>
      <div className="status-main">
        <Tooltip title={getTooltipContent()}>
          <Badge 
            status={config.badgeStatus}
            text={
              <span 
                className="status-text" 
                onClick={showDetails ? () => setDetailsVisible(!detailsVisible) : undefined}
                style={{
                  color: config.color,
                  cursor: showDetails ? 'pointer' : 'default'
                }}
              >
                {config.icon}
                <span className="status-label">{config.text}</span>
                {responseTime && !showDetails && (
                  <span className="response-time">({responseTime}ms)</span>
                )}
                {healthScore !== undefined && !showDetails && (
                  <span className="health-score">[{healthScore}%]</span>
                )}
              </span>
            }
          />
        </Tooltip>
        
        {showTestButton && onTest && (
          <Button 
            size="small" 
            icon={<ReloadOutlined />}
            onClick={onTest}
            loading={status === 'checking'}
            className="test-button"
            title="测试连接"
          >
            {size === 'small' ? '' : '测试'}
          </Button>
        )}
        
        {showDetails && (
          <Button 
            size="small"
            type="text"
            icon={<InfoCircleOutlined />}
            onClick={() => setDetailsVisible(!detailsVisible)}
            className="details-button"
            title="查看详细状态"
          />
        )}
      </div>
      
      {detailsVisible && renderDetailedStatus()}
    </div>
  );
};

export default ModelStatusIndicator;
export type { ModelStatusIndicatorProps };